<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="HandheldFriendly" content="true"/>

  <title>WEBSOCKET Text iink</title>

  <link rel="stylesheet" href="../examples.css">

  <script src="https://code.jquery.com/pep/0.4.3/pep.js"></script>
  <script type="text/javascript" src="../../dist/iink.min.js"></script>
</head>

<body>

<div>
  <nav>
    <div class="languages">
      <select id="language"></select>
    </div>
    <div class="spacer"></div>
    <div class="search">
      <input id="searchInput" type="search" class="input-field">
      <button id="searchBtn" class="classic-btn">Search</button>
    </div>
    <div class="spacer"></div>
    <button class="classic-btn" id="convert" disabled>Convert</button>
  </nav>
  <div id="editor" touch-action="none"></div>
</div>
<script>
  const editorElement = document.getElementById('editor');
  const languageElement = document.getElementById('language');
  const convertElement = document.getElementById('convert');
  const searchInput = document.getElementById('searchInput');
  const searchBtn = document.getElementById('searchBtn');
  let lastJiix = undefined;

  // Utility function transforming millimeters to pixel as iinkSDK is millimeters only
  function mmToPixel(mm) {
    return ((96 * mm) / 25.4)
  }

  // Highlight a series of words (jiix structure) by creating a div with a lower z-index
  function highlightWords(words) {
    words.forEach(word => {
      const boundingBox = word['bounding-box'];
      const newElement = document.createElement("div");
      newElement.style.position = "absolute";
      newElement.style.left = mmToPixel(boundingBox.x) + "px";
      newElement.style.top = (88 + mmToPixel(boundingBox.y)) + "px";
      newElement.style.height = mmToPixel(boundingBox.height) + "px";
      newElement.style.width = mmToPixel(boundingBox.width) + "px";

      newElement.classList.add('highlight');
      newElement.style.backgroundColor = "yellow";
      newElement.style.zIndex = 11;

      document.body.appendChild(newElement);
    })
  }


  // Perform the search by iterating the last jiix received and ignoring the carriage returns and blank in it.
  function performSearch() {
    document.querySelectorAll('.highlight').forEach(elem => elem.parentNode.removeChild(elem));

    if(searchInput.value && lastJiix) {
      searchWords = searchInput.value.split(" ");
      let posUnderEvaluation = 0;
      let wordsToHighlight = [];


      lastJiix.words.forEach(word => {
        const searchWord = searchWords[posUnderEvaluation];
        if (word.label.trim() !== "") {
          if (word.label.toUpperCase() === searchWord.toUpperCase()) {
            wordsToHighlight.push(word);
            if (posUnderEvaluation === (searchWords.length - 1)) {
              highlightWords(wordsToHighlight);
              posUnderEvaluation = 0;
              wordsToHighlight = [];
            } else {
              posUnderEvaluation++;
            }
          } else {
            posUnderEvaluation = 0;
            wordsToHighlight = [];
          }
        }
      });
    }
  }
  searchBtn.addEventListener('click', performSearch);

  editorElement.addEventListener('exported', (evt) => {
    const exports = evt.detail.exports;
    if (exports) {
      convertElement.disabled = false;
      if (exports['application/vnd.myscript.jiix']) {
        lastJiix = JSON.parse(exports['application/vnd.myscript.jiix']);
        performSearch();
      }
    }
  });

  editorElement.addEventListener('loaded', async (evt) => {
    /**
     * Retrieve the list of available recognition languages
     * @param {Object} The editor recognition parameters
     */
    const currentLanguage = evt.target.editor.configuration.recognitionParams.iink.lang;
    const res = await iink.getAvailableLanguageList(evt.target.editor.configuration);

    if (languageElement.options.length === 0) {
      Object.keys(res.result).forEach((key) => {
        const selected = currentLanguage === key;
        languageElement.options[languageElement.options.length] = new Option(res.result[key], key, selected, selected);
      });
    }
  });

  editorElement.addEventListener('changed',() => {
    document.querySelectorAll('.highlight').forEach(elem => elem.parentNode.removeChild(elem));
  });

  languageElement.addEventListener('change', (e) => {
    const configuration = editorElement.editor.configuration;
    //The path to the language depend of the version of API you are using.
    configuration.recognitionParams.iink.lang = e.target.value;
  });

  convertElement.addEventListener('click', () => {
    editorElement.editor.convert();
  });

  /**
   * Attach an editor to the document
   * @param {Element} The DOM element to attach the ink paper
   * @param {Object} The recognition parameters
   */
  iink.register(editorElement, {
    recognitionParams: {
      type: 'TEXT',
      protocol: 'WEBSOCKET',
      server: {
        scheme: 'https',
        host: 'webdemoapi.myscript.com',
        applicationKey: '515131ab-35fa-411c-bb4d-3917e00faf60',
        hmacKey: '54b2ca8a-6752-469d-87dd-553bb450e9ad'
      },
      iink: {
        export: {
          jiix: {
            'bounding-box': true,
          }
        },
        text: {
          smartGuide: false
        }
      }
    }
  });

  window.addEventListener('resize', () => {
    editorElement.editor.resize();
  });
</script>
</body>

</html>